<template>
  <el-dialog
    title="交班信息"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    :width="device == 'desktop' ? '70%' : '90%'"
    v-dialog-drag
    :close-on-click-modal="false"
    :destroy-on-close="true"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <div class="dialog-body-content" :key="updateKey" v-loading="loading">
      <el-collapse
        :value="[
          '1',
          'members',
          'task',
          'rawMaterial',
          'equipOperationStatus',
          'taskProcessingStatus',
          'abnormalHandlingStatus',
          'stationLog',
        ]"
      >
        <el-collapse-item name="1">
          <template slot="title">
            <PartitionTitle title="交班详情"></PartitionTitle>
          </template>
          <el-form
            ref="BaseForm"
            :model="baseForm"
            :rules="rules"
            label-width="150px"
            size="small"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属车间" prop="workshopName">
                  <el-input
                    type="text"
                    v-model="baseForm.workshopName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产线" prop="lineName">
                  <el-input
                    type="text"
                    v-model="baseForm.lineName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="班组" prop="groupName">
                  <el-input
                    type="text"
                    v-model="baseForm.groupName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="实际工作开始时间" prop="workStartTime">
                  <el-input
                    type="text"
                    v-model="baseForm.workStartTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实际工作结束时间" prop="workEndTime">
                  <el-date-picker
                    v-model="baseForm.workEndTime"
                    type="datetime"
                    placeholder="选择实际工作结束时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    @change="handleProduceTimeDurChange"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计划停机时长(小时)" prop="planDowntimeDur">
                  <el-input
                    type="text"
                    v-model="baseForm.planDowntimeDur"
                    @change="handleProduceTimeDurChange"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="班组生产时长(小时)" prop="produceTimeDur">
                  <el-input
                    type="text"
                    v-model="baseForm.produceTimeDur"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="下一班是否连续生产"
                  prop="continuousProduce"
                >
                  <!-- 更新交班信息时，不能修改该字段内容 -->
                  <div class="box">
                    <el-select
                      v-model="baseForm.continuousProduce"
                      placeholder="请选择"
                      class="w1"
                      :disabled="group && group.status === 'HANDOVERED'"
                      @change="handleContinuousProduceChange"
                    >
                      <el-option label="是" value="Y"> </el-option>
                      <el-option label="否" value="N"> </el-option>
                    </el-select>
                    <el-select
                      v-if="showNotContinuousReason"
                      v-model="baseForm.notContinuousReason"
                      placeholder="请选择"
                      :disabled="group && group.status === 'HANDOVERED'"
                      @change="handleBaseFormChange"
                    >
                      <el-option label="换型" value="换型"> </el-option>
                      <el-option label="停机" value="停机"> </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否头班">
                  <el-input
                    type="text"
                    :value="baseForm.preProduceLogId ? '否' : '是'"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 原材料信息 -->
          <RawMaterial
            v-if="
              handoverDetail &&
              !['WATER', 'ALLOCATE', 'PRODUCTION_PUBLIC'].includes(
                handoverDetail.workshopType
              )
            "
            status="2"
          ></RawMaterial>
          <Members status="2" detailKey="handoverDetail"></Members>
          <!-- 设备运行情况 -->
          <EquipOperationStatus></EquipOperationStatus>
          <!-- 任务处理情况 -->
          <TaskProcessingStatus
            :status="group && group.status === 'PRODUCING' ? '2' : '3'"
          ></TaskProcessingStatus>
          <!-- 异常处理情况 -->
          <AbnormalHandlingStatus
            :status="group && group.status === 'PRODUCING' ? '2' : '3'"
          ></AbnormalHandlingStatus>
          <!-- 工位交接日志 -->
          <StationLog status="2"></StationLog>
        </el-collapse-item>
      </el-collapse>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="default"
        :loading="saveloading"
        @click="dialogVisible = false"
        >取消</el-button
      >
      <el-button
        v-if="group && group.status === 'PRODUCING'"
        type="primary"
        :disabled="!handoverDetail"
        :loading="saveloading"
        @click="handleSubmit"
        >确认交班</el-button
      >
      <el-button
        v-if="group && group.status === 'HANDOVERED'"
        type="primary"
        :disabled="!handoverDetail"
        :loading="saveloading"
        @click="handleUpdate"
        >更新交班信息</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import Members from "../components/members";
import RawMaterial from "../components/rawMaterial";
import EquipOperationStatus from "../components/equipOperationStatus";
import TaskProcessingStatus from "../components/taskProcessingStatus";
import AbnormalHandlingStatus from "../components/abnormalHandlingStatus";
import StationLog from "../components/stationLog";
import {
  getHandoverDetail,
  saveHandover,
  confirmHandover,
} from "@/api/shifts/shiftHandover";
import { getHistoryDetail } from "@/api/shifts/history";
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  components: {
    Members,
    RawMaterial,
    EquipOperationStatus,
    TaskProcessingStatus,
    AbnormalHandlingStatus,
    StationLog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    group: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      updateKey: 1,
      loading: false,
      saveloading: false,
      baseForm: {
        workshopName: null,
        lineName: null,
        groupName: null,
        workStartTime: null,
        continuousProduce: "Y",
        notContinuousReason: null,
        planDowntimeDur: null,
        produceTimeDur: null,
        workEndTime: null,
        preProduceLogId: null,
      },
      rules: {
        planDowntimeDur: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入数字，最多保留两位小数",
            trigger: "blur",
          },
        ],
        workEndTime: [
          {
            validator: (rule, value, callback) => {
              const startTime = this.baseForm?.workStartTime || null;
              if (!startTime || !value) {
                callback();
                return;
              }
              const startDatetime = new Date(startTime);
              const endDatetime = new Date(value);
              if (startDatetime > endDatetime) {
                callback(new Error("结束时间不能早于开始时间"));
                return;
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      },
      showNotContinuousReason: false,
    };
  },
  computed: {
    ...mapGetters(["device"]),
    ...mapState({
      handoverDetail: (state) => state.turnOnDuty.handoverDetail,
    }),
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
  },
  methods: {
    ...mapMutations("turnOnDuty", ["SET_TAKEOVERDETAIL", "SET_HANDOVERDETAIL"]),
    handleClose() {
      this.SET_TAKEOVERDETAIL(null);
      this.SET_HANDOVERDETAIL(null);
    },
    handleOpen() {
      this.getDetails();
      // 每次打开，默认显示当前时间
      this.baseForm.workEndTime = this.parseTime(
        new Date(),
        "{y}-{m}-{d} {h}:{i}:{s}"
      );
    },
    getDetails() {
      if (!this.group?.id) {
        return;
      }
      this.loading = true;

      let getDetailFn = getHandoverDetail;
      if (this.group.status == "HANDOVERED") {
        // 已交班的，通过getHistoryDetail获取最新数据，做更新交班信息
        getDetailFn = getHistoryDetail;
      }
      getDetailFn(this.group.id)
        .then((res) => {
          this.SET_HANDOVERDETAIL(res?.data || null);
          const {
            workshopName,
            lineName,
            groupName,
            workStartTime,
            continuousProduce,
            notContinuousReason,
            planDowntimeDur,
            produceTimeDur,
            workEndTime,
            preProduceLogId,
          } = res.data;
          this.baseForm = {
            workshopName,
            lineName,
            groupName,
            workStartTime,
            continuousProduce:
              continuousProduce || this.baseForm.continuousProduce,
            notContinuousReason,
            planDowntimeDur: planDowntimeDur
              ? this.toFix(planDowntimeDur, 2)
              : planDowntimeDur,
            produceTimeDur,
            workEndTime: workEndTime || this.baseForm.workEndTime,
            preProduceLogId,
          };
          this.handleContinuousProduceChange(this.baseForm.continuousProduce);
          this.updateKey++;
          this.loading = false;
        })
        .catch(() => {
          this.SET_HANDOVERDETAIL(null);
          this.baseForm = {
            workshopName: null,
            lineName: null,
            groupName: null,
            workStartTime: null,
            continuousProduce: "Y",
            notContinuousReason: null,
            planDowntimeDur: null,
            produceTimeDur: null,
            workEndTime: null,
            preProduceLogId: null,
          };
          this.updateKey++;
          this.loading = false;
        });
    },
    // 更新详情数据
    handleBaseFormChange() {
      if (!this.handoverDetail) {
        return;
      }
      let object = Object.assign(this.handoverDetail, this.baseForm);
      this.SET_HANDOVERDETAIL(object);
    },
    // 修改实际工作结束时间 / 修改停机时长, 班组生产时长值随之改变
    handleProduceTimeDurChange() {
      if (!this.baseForm.workStartTime || !this.baseForm.workEndTime) {
        return;
      }

      // 实际工作结束时间和计划停机时长(小时)字段都输入正确，才进行计算
      let _flag = "";
      this.$refs.BaseForm.validateField(
        ["workEndTime", "planDowntimeDur"],
        (flag) => {
          _flag = flag || _flag;
        }
      );
      if (_flag) {
        return;
      }

      const planDowntimeDur = Number(this.baseForm.planDowntimeDur) || 0;
      const workStartTimeTamp = new Date(this.baseForm.workStartTime).getTime();
      const workEndTimeTamp = new Date(this.baseForm.workEndTime).getTime();
      const planDowntimeDurTamp = planDowntimeDur * 60 * 60 * 1000;
      this.baseForm.produceTimeDur =
        Math.round(
          (100 * (workEndTimeTamp - workStartTimeTamp - planDowntimeDurTamp)) /
            1000 /
            60 /
            60
        ) / 100;
      this.handleBaseFormChange();
    },
    handleContinuousProduceChange(value) {
      if (value == "Y") {
        this.baseForm.notContinuousReason = null;
        this.showNotContinuousReason = false;
      } else {
        this.showNotContinuousReason = true;
      }
      this.handleBaseFormChange();
    },
    // 详情保存的参数
    getParams() {
      if (!this.handoverDetail) {
        return null;
      }
      const {
        produceLogId,
        continuousProduce,
        notContinuousReason,
        planDowntimeDur,
        factoryDeptId,
        factoryDeptCode,
        workshopId,
        lineId,
        groupId,
        produceDate,
        workEndTime,
        produceTimeDur,
        logMaterialDtos,
        orderDtos,
        workStationUserVos,
        preProduceLogId,
        workshopType,
        allUndoMissionIds,
        remainMissionIds,
        allUndoAbnormalIds,
        remainAbnormalIds,
      } = this.handoverDetail;
      const params = {
        produceLogId,
        continuousProduce,
        notContinuousReason,
        planDowntimeDur,
        factoryDeptId,
        factoryDeptCode,
        workshopId,
        lineId,
        groupId,
        produceDate,
        workEndTime,
        produceTimeDur,
        logMaterialDtos:
          logMaterialDtos?.map((ele) => ({
            id: ele.id,
            produceLogId: ele.produceLogId,
            itemNo: ele.itemNo,
            ifExtend: ele.ifExtend,
            refundQty: ele.refundQty,
            preGroupBlcQty: ele.preGroupBlcQty,
            currentGroupBlcQty: ele.currentGroupBlcQty,
          })) || [],
        orderDtos:
          orderDtos?.map((ele) => ({
            id: ele.id,
            erpOrderNo: ele.erpOrderNo,
            actualStarttime: ele.actualStarttime,
            actualEndtime: ele.actualEndtime,
            collectedQuantity: ele.collectedQuantity,
            actualQuantity: ele.actualQuantity,
            orderSn: ele.orderSn,
            groupProduceLogId: ele.groupProduceLogId,
            orderMaterialDtos: ele.orderMaterialDtos.map((or) => ({
              id: or.id,
              orderId: or.orderId,
              itemNo: or.itemNo,
              planQty: or.planQty,
              ptsPickingQty: or.ptsPickingQty,
              ptsRefundQty: or.ptsRefundQty,
              collectWastageQty: or.collectWastageQty,
              actualWastageQty: or.actualWastageQty,
              theoryConsumeQty: or.theoryConsumeQty,
              currentBalanceQty: or.currentBalanceQty,
              remark: or.remark,
            })),
          })) || [],
        workStationUserVos:
          workStationUserVos?.map((ele) => ({
            workStationId: ele.workStationId,
            workType: ele.workType,
            workStationUserHourVos:
              ele.workStationUserHourVos?.map((user) => ({
                username: user.username,
                workHours: user.workHours,
              })) || [],
          })) || [],
        preProduceLogId,
        workshopType,
        allUndoMissionIds,
        remainMissionIds,
        allUndoAbnormalIds,
        remainAbnormalIds,
      };

      // 每个工位必须配人
      const emtyUser = params.workStationUserVos.find(
        (ele) => !ele.workStationUserHourVos?.length
      );
      if (emtyUser) {
        this.msgWarning("每个工位必须分配人员");
        return null;
      }

      // 每个工单的实际结束时间不能大于实际开始时间
      const errorTime = params.orderDtos.find(
        (ele) =>
          new Date(ele.actualStarttime).getTime() > new Date(ele.actualEndtime)
      );
      if (errorTime) {
        this.msgWarning("工单实际开始时间不能大于实际结束时间");
        return null;
      }

      return params;
    },
    // 更新交班信息
    handleUpdate() {
      this.$refs.BaseForm.validate((flag) => {
        if (flag) {
          this.$confirm("是否确定更新交班信息？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              const params = this.getParams();
              if (!params) {
                return Promise.reject();
              }
              this.saveloading = true;
              return saveHandover(params);
            })
            .then((res) => {
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        }
      });
    },
    // 确认交班
    handleSubmit() {
      this.$refs.BaseForm.validate((flag) => {
        if (flag) {
          this.$confirm("是否确定结束工作？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              const params = this.getParams();
              if (!params) {
                return Promise.reject();
              }
              this.saveloading = true;
              return confirmHandover(params);
            })
            .then((res) => {
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-collapse {
  border: none;
  .el-collapse-item__wrap {
    border: none;
  }
}
.block-title {
  margin-bottom: 0;
}
.box {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}
::v-deep .el-dialog__body {
  .el-date-editor.el-input {
    width: 100%;
  }
}
.el-select {
  width: 100%;
}
</style>
